import { ref, onMounted } from 'vue';
import { listProject } from '@/api/proj/project';

// 全局缓存，避免重复请求
let cachedOptions: { label: string; value: string | number }[] | null = null;

export function useProjectListOptions() {
  const projectOptions = ref<{ label: string; value: string | number }[]>([]);
  const loading = ref(false);

  const loadOptions = async () => {
    if (cachedOptions) {
      projectOptions.value = cachedOptions;
      return;
    }

    loading.value = true;
    try {
      const res = await listProject(); // 获取全部项目
      const options = res.rows.map((item) => ({
        label: item.projectName, // 显示名
        value: item.projectId // 实际值
      }));
      projectOptions.value = options;
      cachedOptions = options; // 缓存
    } finally {
      loading.value = false;
    }
  };

  // 自动加载（可选）
  onMounted(() => {
    if (!cachedOptions) {
      loadOptions();
    }
  });

  return {
    projectOptions,
    loading,
    reload: loadOptions // 手动刷新
  };
}
